const { getPage, getBrowser, closePage } = require("../utils/browserPage");
const { PerformanceCollect } = require("../utils/performanceCollect");
const { lighthousePerformance } = require("../utils/lighthouse");
const { calcScore } = require("../utils/calc")
/**
 * 执行性能检测
 * @param {*}} ctx 
 */
async function checkPerformance(ctx){
    ctx.verifyParams({
        url: {type: "string", required: true}
    })
    const page = getPage();
    const { url } = ctx.request.body;
    if(!!page){
        try{
            await page.goto(url);
            const performanceTiming = JSON.parse(
                await page.evaluate(() => JSON.stringify(window.performance))
            );
            const performanceData = {
                performance: new PerformanceCollect(performanceTiming.timing),
                lighthouse: await lighthousePerformance(url, getBrowser())
            }
            const score = calcScore(performanceData)
            // 归还page:
            closePage(page);
            ctx.body = {
                errno: 0,
                performanceData,
                score
            }
        }catch(e){
            ctx.body = {
                errno: -1,
                message: "Please check that the check URL is correct"
            }
        }
    }else{
        ctx.body = {
            errno: -1,
            message: "The service is under preparation. Please wait for a while and try again"
        }
    }
}

module.exports = {
    checkPerformance
}